<?php
declare (strict_types=1);

namespace app\model\home;

use app\common\model\BaseModel;
use app\common\model\Member;
use app\common\model\Store;
use \libs\Log;

class Duty extends BaseModel
{
    protected $pk = 'id';

    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * @param $value
     * @return mixed|string
     * 头像
     */
    protected function getAvatarAttr($value)
    {
        return Assistant::where('id', $value)->value('avatar') ?: '';
    }

    /**
     * @param $value
     * @return mixed|string
     * 门店名称
     */
    protected function getStoreNameAttr($value)
    {
        return Store::where('id', $value)->value('store_name') ?: '';
    }

    /**
     * @param $value
     * @return Assistant|array|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 用户信息
     */
    protected function getUserAttr($value)
    {
        $info = Assistant::where('id', $value)->field('nickname,address,avatar')->find();
        return $info ?: [];
    }

    /**
     * 获得列表
     * @param bool $where
     * @param string $fields
     * @param string|null $order
     * @param int $page
     * @param int $pageSize
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList($where = [], string $fields = '*', string $order = null, int $page = 1, int $pageSize = 20, $params)
    {
        $data = [
            'count' => 0,
            'list' => []
        ];
        $reType = $where['re_type'];
        $status = $where['status'];
        $assId = Assistant::where('member_id', $params['member_id'])->value('id');
        if ($where['status'] != 3) {
            $where = [
                ['re_id', '=', $assId],
                ['re_type', '=', $reType],
                ['status', '=', $status]
            ];
        } else {
            $where = [
                ['re_id', '<>', $assId],
                ['re_type', '=', $reType],
                ['status', '=', $status]
            ];
        }
        $count = $this->where([$where])->count();
        if (empty($count)) {
            return $this->returnRight($data);
        }
        $order = is_null($order) ? $this->pk . ' desc' : $order;
        $list = $this->where([$where])
            ->field($fields)
            ->order($order)
            ->page($page, $pageSize)
            ->select();
        $listArr = [];
        $data['count'] = $count;
        if (!empty($list->toArray())) {
            foreach ($list->toArray() as $item) {
                //班次
                $dutyTime = strtotime($item['duty_date'] . ' ' . $item['start_timestr']);
                $diffTime = $dutyTime - strtotime(date('Y-m-d 23:59:59', time()));
                if (($diffTime < 0 && abs($diffTime) > 86400)) {
                    $item['click_status'] = 0;
                } elseif ($diffTime <= 1800) {
                    $item['click_status'] = 0;
                } else {
                    $item['click_status'] = 1;
                }
                $item['time_str'] = $item['start_timestr'] . '-' . $item['end_timestr'];
                $listArr[] = $item;
            }
        } else {
            $data['count'] = 0;
        }
        $data['count'] = $count;
        $data['list'] = $listArr;
        return $this->returnRight($data);
    }

    /**
     * @param $data
     * @return array
     * 新增
     */
    public function add($data)
    {
        //根据用户身份获取助教id
        $data['re_id'] = Assistant::where('member_id', $data['member_id'])->value('id');
        $data['start_timestr'] = $data['start_time'];
        $data['end_timestr'] = $data['end_time'];
        //获取已报班的日期
        $map['re_id'] = $data['re_id'];
        $map['re_type'] = 1;
        $map['status'] = 1;
        $map['duty_date'] = $data['duty_date'];
        $usedArr = $this->where($map)->field('start_timestr,end_timestr,duty_date')->select();
//        dd($usedArr->toArray());
        if (!empty($usedArr->toArray())) {
            foreach ($usedArr->toArray() as $v) {
                $usedTimeArr[] = strtotime($v['duty_date'] . ' ' . $v['start_timestr']);
                $usedTimeArr[] = strtotime($v['duty_date'] . ' ' . $v['end_timestr']);
            }
            $usedTimeArr = array_unique($usedTimeArr);
            $min = min($usedTimeArr);
            $max = max($usedTimeArr);
            $startAt = strtotime($data['duty_date'] . ' ' . $data['start_time']);
            $endAt = strtotime($data['duty_date'] . ' ' . $data['end_time']);

            if (($startAt >= $min && $startAt <= $max) || ($endAt <= $max && $endAt >= $min)) {
                return $this->returnError(30);
            }
            if (empty($data['re_id'])) {
                return $this->returnError(29);
            }
        }
        self::create($data);
        return $this->returnSucc();
    }

    /**
     * @param $data
     * @param $value
     * @return array
     * 改变值班状态
     */
    public function changeStatus($data, $value)
    {
        $where['id'] = $data['id'];
        $data['status'] = $value;
        $assId = Assistant::where('member_id', $data['member_id'])->value('id');
        $data['re_id'] = $assId;
        //顶班
        if ($value == 2) {
            //查看自己的报班
            $map['status'] = 1;
            $map['re_id'] = $assId;
            $usedArr = $this->where($map)->whereOr('status', 2)->field('duty_date,start_timestr,end_timestr')->select();
            if (!empty($usedArr->toArray())) {
                foreach ($usedArr->toArray() as $v) {
                    $usedTimeArr[] = strtotime($v['duty_date'] . ' ' . $v['start_timestr']);
                    $usedTimeArr[] = strtotime($v['duty_date'] . ' ' . $v['end_timestr']);
                }
                $usedTimeArr = array_unique($usedTimeArr);
                $min = min($usedTimeArr);
                $max = max($usedTimeArr);
                //顶班的时间
                $info = $this->where('id', $data['id'])->field('duty_date,start_timestr,end_timestr')
                    ->find();
                $startAt = strtotime($info['duty_date'] . ' ' . $info['start_timestr']);
                $endAt = strtotime($info['duty_date'] . ' ' . $info['end_timestr']);
                if (($startAt >= $min && $startAt <= $max) || ($endAt <= $max && $endAt >= $min)) {
                    return $this->returnError(31);
                }
            }
        }
        $res = $this->allowField(['id,status'])->update($data, $where);
        if ($res) {
            return $this->returnSucc();
        } else {
            return $this->returnError(1);
        }
    }

    /**
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 每周当值
     */
    public function weekData($where, $page, $pageSize, $data)
    {
        $listArr = $this->where([$where])->whereTime('duty_date', 'week')->field('id,re_id,re_id avatar,store_id,duty_date,start_timestr,end_timestr')->page($page, $pageSize)->select();
        foreach ($listArr->toArray() as $item) {
            $item['virtual_avatar'] = get_rand_one_virtual_avatar();
            $listAll[] = $item;
        }
        return $this->returnRight($listAll);
    }
}
